#include "Wifi_user.h"
#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <FreeRTOS.h>
#include "ArduinoJson.h"
#include "my_demo.h"

#define WIFI_UID "****" //填入WiFi账户
#define WIFI_PSD "****" //填入WiFi密码

TaskHandle_t NetTask_Handler;

//定义操作区
DynamicJsonDocument doc(2048);

struct tm timeinfo;
const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 8 * 3600;
const int   daylightOffset_sec = 0;

void Net_task(void *pvParameters)
{
    while(1)
    {
        my_wifi_hander();
        delay(1000);
        String atm = doc["results"][0]["now"]["text"];
        String tem = doc["results"][0]["now"]["temperature"];
        String code = doc["results"][0]["now"]["code"];
        char m_temp[50];
        sprintf(m_temp,"天气:%s  温度:%s",atm.c_str(),tem.c_str());
        demo_set_data_and_weatner(timeinfo.tm_year,timeinfo.tm_mon,timeinfo.tm_mday,timeinfo.tm_hour,timeinfo.tm_min,timeinfo.tm_wday,code.toInt(),m_temp);
    }
}   

void my_wifi_init()
{
    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    WiFi.begin(WIFI_UID,WIFI_PSD);
    printf("connecting!");
    while(!WiFi.isConnected())
    {
        printf(".");
        delay(500);
    }
    printf("is connect\n");
    Serial.println(WiFi.localIP());

    configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

    my_wifi_hander();

    xTaskCreate((TaskFunction_t )Net_task,     	
                (const char*    )"net_task",   	
                (uint16_t       )50000, 
                (void*          )nullptr,				
                (UBaseType_t    )configMAX_PRIORITIES-2,	
                (TaskHandle_t*  )&NetTask_Handler);
}

void Time_Hander()
{
    if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
    }
    // printf("%d/%d/%d\n",timeinfo.tm_year,timeinfo.tm_mon,timeinfo.tm_mday);
    // printf("%d:%d:%d %d\n",timeinfo.tm_hour,timeinfo.tm_min,timeinfo.tm_sec,timeinfo.tm_wday);
}

void Client_Hander()
{
    WiFiClient client;
    if (client.connect("api.seniverse.com", 80) == 1)//连接服务器判断连接
    {
        //***换成心知天气申请的私钥
        //yixing改成你所在城市的拼音
        String str;
        client.print("GET /v3/weather/now.json?key=***&location=yixing&language=zh-Hans&unit=c HTTP/1.1\r\n"); //心知天气的URL格式
        client.print("Host:api.seniverse.com\r\n");
        client.print("Accept-Language:zh-cn\r\n");
        client.print("Connection:close\r\n\r\n");//向心知天气的服务器发送请求。
        //String status_code = client.readStringUntil('\r');
        //读取GET数据，服务器返回成功则返回状态码200
        //Serial.println(status_code);
        if (client.find("\r\n\r\n") == 1)//跳过数据头，读取JSON数据，
        {
            String json_from_server = client.readStringUntil('\n'); //读取JSON数据
//            Serial.println(json_from_server);
            deserializeJson(doc,json_from_server);
            String test = doc["results"][0]["now"]["code"];
            Serial.printf("code:");
            Serial.println(test.c_str());
        }
    }
    client.stop(); 
}

void my_wifi_hander()
{
    if(!WiFi.isConnected())
    {
        return;
    }
    //上来首次调用就能获得天气和时间
    static int i=6;
    i++;
    if(i==7)
    {
        Client_Hander();
        i=0;
    }
    Time_Hander();
}
